//
//  productCenterVC.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/9/7.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "shareCenterVC.h"
#import "childBaseTableViewCell.h"
#import "BPhttpTool.h"
#import "AccountTool.h"
#import "shareModel.h"
#import "MBProgressHUD+MJ.h"
#import "MJExtension.h"
#import "composeVC.h"
#import <ShareSDK/ShareSDK.h>

#define shareUrl @"http://ttmy.len.so/home/appinvite/workshow/id/"

@interface shareCenterVC ()<childBaseTableViewCellDelegate,UITableViewDataSource,UITableViewDelegate>{
    BOOL _isfirst;
}

@property (nonatomic,strong)NSMutableArray *shareArry;

@property (nonatomic,strong)NSMutableArray *againArry;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)UITableView *shareTableView;

@end

@implementation shareCenterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _isfirst = YES;
    self.shareArry = [NSMutableArray array];
    self.againArry = [NSMutableArray array];
    [self getOrderData];
    
    [self setUpTableView];
    
    [self addTopButton]; 
}

- (void)getOrderData
{
    [BPhttpTool get:[NSString stringWithFormat:@"%@works/getlist/uid/%@",BPhttp,[AccountTool account].uid] params:nil success:^(id responseObj) {
        NSArray *arry = [shareModel objectArrayWithKeyValuesArray:responseObj];
        for (shareModel *model in arry) {
            if ([model.isshare intValue] == 0) {
                [self.shareArry addObject:model];
            }else{
                [self.againArry addObject:model];
            }
        }
        if (_isfirst == YES) {
            self.dataArray = self.shareArry;
            _isfirst = NO;
        }
        [self.shareTableView reloadData];
    } failure:^(NSError *error) {
        BPLog(@"获取失败");
    }];
}

- (void)setUpTableView{
    shareManger = [[CoreDateManager alloc] init];
    
    CGFloat tableViewY = BPScreenNavY + 50.0f;
    UITableView *shareTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableViewY, BPScreenW, BPScreenH - tableViewY)];
    shareTableView.backgroundColor = [UIColor whiteColor];
    shareTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    shareTableView.delegate = self;
    shareTableView.dataSource = self;
    [self.view addSubview:shareTableView];
    self.shareTableView = shareTableView;
}

- (void)addTopButton
{
    NSArray *buttonName = [NSArray arrayWithObjects:@"未分享",@"已分享", nil];
    for (int i = 0; i < 2; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = 1000+i;
        CGFloat btnW = BPScreenW  / 2.0f;
        btn.frame = CGRectMake(btnW * i , 0, btnW, self.headView.height);
        BPLineView *line = [[BPLineView alloc] initWithFrame:CGRectMake(btnW * (i + 1), 10, 1, btn.height - 20)];
        [btn setTitle:buttonName[i] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.headView addSubview:btn];
        [self.headView addSubview:line];
    }
}

//top按钮点击事件
- (void)btnClick:(UIButton *)button
{
    if (button.tag == 1000) {
        self.dataArray = self.shareArry;
        [self.shareTableView reloadData];
        
    }else {
        self.dataArray = self.againArry;
        [self.shareTableView reloadData];
        
    }
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    childBaseTableViewCell *cell = [childBaseTableViewCell cellWithTableView:tableView];
    
    cell.backgroundColor = [UIColor clearColor];
    
    cell.delegate = self;
    
    [cell setUpShareCell:self.dataArray[indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}

//分享作品
- (void)shareProduct:(childBaseTableViewCell *)childBaseCell
{
    NSIndexPath *indexPath = [self.shareTableView indexPathForCell:childBaseCell];
    shareModel *model = self.dataArray[indexPath.row];
    
    composeVC *compose = [[composeVC alloc] init];
    compose.workID = model.iD;
    compose.imageUrl = model.picture;
    compose.block = ^(){
        [self.shareArry removeObject:model];
        [self.againArry addObject:model];
        [self.shareTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:compose animated:YES];
}

//再次分享
- (void)shareAgain:(childBaseTableViewCell *)childBaseCell
{
    
    NSIndexPath *indexPath = [self.shareTableView indexPathForCell:childBaseCell];
    shareModel *model = self.dataArray[indexPath.row];
   // NSLog(@"%@",[NSString stringWithFormat:@"%@%@",pictureUrl,model.picture]);
    id<ISSContent> publishContent = [ShareSDK content:model.title
                                       defaultContent:@""
                                                image:[ShareSDK imageWithUrl:[NSString stringWithFormat:@"%@%@",pictureUrl,model.picture]]
                                                title:@"天天美印"
                                                  url:[NSString stringWithFormat:@"%@%@",shareUrl,model.iD]
                                          description:@"天天美印个人作品"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:nil arrowDirect:UIPopoverArrowDirectionUp];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                                scopes:nil
                                                         powerByHidden:YES
                                                        followAccounts:nil
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    id<ISSShareOptions> shareOptions = [ShareSDK defaultShareOptionsWithTitle:nil
                                                              oneKeyShareList:[NSArray defaultOneKeyShareList]
                                                               qqButtonHidden:YES
                                                        wxSessionButtonHidden:YES
                                                       wxTimelineButtonHidden:YES
                                                         showKeyboardOnAppear:NO
                                                            shareViewDelegate:nil
                                                          friendsViewDelegate:nil
                                                        picViewerViewDelegate:nil];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:authOptions
                      shareOptions:shareOptions
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSPublishContentStateSuccess)
                                {
                                    [MBProgressHUD showSuccess:@"发表成功"];
                                }
                                else if (state == SSPublishContentStateFail)
                                {
                                    [MBProgressHUD showError:@"发表失败"];
                                }
                            }];
}

- (void)shanchuCell:(childBaseTableViewCell *)childBaseCell
{
    NSIndexPath *indexPath = [self.shareTableView indexPathForCell:childBaseCell];
    shareModel *model = self.dataArray[indexPath.row];
    int workID = [model.iD intValue];
    if (workID != 0) {
        [BPhttpTool get:[NSString stringWithFormat:@"%@works/delete/id/%d",BPhttp,workID] params:nil success:^(id responseObj) {
            NSDictionary *dic = responseObj;
            if ([dic[@"status"] intValue] == 1) {
                [shareManger deletOneProduct:model.iD];
                [MBProgressHUD showSuccess:@"删除成功"];
            }
            
        } failure:^(NSError *error) {
            BPLog(@"分享失败");
        }];
    }
    [self.dataArray removeObjectAtIndex:indexPath.row];
    [self.shareTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)shareAgainButton
{
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
